import { Component, Input, OnInit ,ViewChild} from '@angular/core';
import { SFSchema,SFSliderWidgetSchema } from '@delon/form';
import { ApiService } from '@core/services/api';
import { HttpClient } from '@angular/common/http';
import { NzMessageService, NzModalRef, UploadFile } from 'ng-zorro-antd';
import { FormBuilder, FormGroup } from '@angular/forms';
import { UtilService } from '@core/services/util.service';
import { NzTabPosition } from 'ng-zorro-antd/tabs';
import { format } from 'date-fns'
import { version } from 'process';

function getBase64(file: File): Promise<string | ArrayBuffer | null> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

@Component({
  selector: 'device-edit',
  templateUrl: './device-edit.component.html',
  styles: []
})
export class DeviceEditComponent implements OnInit {
  nzTabPosition: NzTabPosition = 'left';
  @ViewChild('formBase',{ static: false }) formBase:any;
  @ViewChild('formVersion',{ static: false }) formVersion:any;
  @ViewChild('formSet',{ static: false }) formSet:any;
  @ViewChild('tree',{static:false}) tree: any;
  @Input()type: 0 | 1;
  @Input()
  set _param(value) {
    console.log(value)
    if (!value) return;
    this.deviceType = value.deviceType
    this.param4=value
    // this.param1 = value;
    this.getDeviceInfo(value.id).then(res => {
      console.log(res);
      let data=res.data.deviceHostRke;
      this.param1={
        
        deviceIp :  data.deviceIp,
        deviceMac :  data.deviceMac,
        deviceCode :  value.deviceCode,
        deviceSizeUsable :  data.deviceSizeUsable,
        deviceSizeSum :  data.deviceSizeSum,
        deviceAppVersion :  data.deviceAppVersion,
        deviceMcuVersion :  data.deviceMcuVersion,
        deviceReadHeadVersion :  data.deviceReadHeadVersion,
        deviceSystemVersion :  data.deviceSystemVersion,
        deviceIpc :  data.deviceIpc,
      }
      this.param2={
        id: data.id,
        deviceOpenFace :  data.deviceOpenFace == "1" ? true : false,
        deviceBioAssay :  data.deviceBioAssay == "1" ? true : false,
        deviceFaceSimilarity :  data.deviceFaceSimilarity,
        deviceBioAssaySimilarity : data.deviceBioAssaySimilarity,
        deviceFaceStorage :  data.deviceFaceStorage,
      },
      this.param3={
        deviceIntercom : data.deviceIntercom  == "1" ? true : false,
        deviceVolumeCall: data.deviceVolumeCall,
        deviceVolumeAdvertising :  data.deviceVolumeAdvertising,
        deviceVolumeMic : data.deviceVolumeMic,
        deviceVolumeBell : data.deviceVolumeBell,
        deviceVolumeHost : data.deviceVolumeHost
      },
      this.param4={
        deviceId :  data.deviceId,
        deviceFacePat :  data.deviceFacePat == "1" ? true : false,
        deviceFacePatVideoUpload : data.deviceFacePatVideoUpload == "1" ? true : false,
        deviceShutScreen :  data.deviceShutScreen == "1" ? true : false,
        deviceAdvertising :  data.deviceAdvertising == "1" ? true : false,
        deviceAccessRecord :  data.deviceAccessRecord == "1" ? true : false,
        deviceAccessRecordPicture :  data.deviceAccessRecordPicture == "1" ? true : false,
        deviceAccessRecordVideo :  data.deviceAccessRecordVideo == "1" ? true : false,
        deviceLed :  data.deviceLed == "1" ? true : false,
        deviceAndroidPassword :  data.deviceAndroidPassword,
        deviceTamperAlarm : data.deviceTamperAlarm == "1" ? true : false,
        deviceDoorOpenAlarm : data.deviceDoorOpenAlarm == "1" ? true : false,
        doorOpenTime : data.doorOpenTime,
        deviceRemark: data.deviceRemark
        // deviceTag :  data.deviceTag == "1" ? true : false,
        // deviceTagType :  data.deviceTagType ,
        // deviceBioAssay :  data.deviceBioAssay == "1" ? true : false,
        // devicePasswordTemporary :  data.devicePasswordTemporary == "1" ? true : false,
        // devicePasswordTime :  data.devicePasswordTime,
        // deviceOpenQr :  data.deviceOpenQr == "1" ? true : false,
        // deviceOpenFace :  data.deviceOpenFace == "1" ? true : false,
        // deviceCamera :  data.deviceCamera == "1" ? true : false,
        // deviceVolumeHost :  data.deviceVolumeHost,
        // deviceVolumeAdvertising :  data.deviceVolumeAdvertising,
      }
      console.log(this.param3)
      // if(this.param.deviceImages) {
      //   this.previewImage = this.param.deviceImages;
      //   this.fileList = [...[{
      //     id: '-1',
      //     status: 'done',
      //     url: this.previewImage
      //   }]]
      // }
    })

  };
  //validateForm!: FormGroup;
  //fileList: any[] = [

  //];
  //uploadUrl = '/network/minIo/uploadFile'
  //previewVisible = false;
  //previewImage: string | undefined = '';
  param1: any;
  param2:any;
  param3:any;
  param4 : any;
  deviceType:number
  houseList = [];
  searchValue:any="";
  isLoading:boolean=true;
  defaultCheckedKeys:any=[];
  showForm = false;
  schema1: SFSchema = {
    properties: {
      deviceIp: {
        type: 'string',
        title: '门禁IP地址',
        ui:{
          grid: {span: 8}
        }
      },
      deviceMac: {
        type: 'string',
        title: '门禁MAC地址',
        ui:{
          grid: {span: 8}
        }
      },
      deviceCode: {
        type: 'string',
        title: '门禁SN',
        ui:{
          grid: {span: 8}
        }
      },
      deviceAppVersion: {
        type:'string',
        title:'门禁APP版本',
        ui:{
          grid: {span: 8}
        }
      },
      deviceMcuVersion: {
        type:'string',
        title:'门禁MCU版本',
        ui:{
          grid: {span: 8}
        }
      },
      deviceReadHeadVersion:{
        type:'string',
        title:'门禁读头版本',
        ui:{
          grid: {span: 8}
        }
      },
      deviceSystemVersion: {
        type:'string',
        title:'门禁系统版本',
        ui:{
          grid: {span: 8}
        }
      },
      deviceIpc: {
        type:'string',
        title:'门禁IPC版本',
        ui:{
          grid: {span: 8}
        }
      },
      deviceSizeUsable: {
        type:'string',
        title:'门禁可用容量',
        ui:{
          grid: {span: 8}
        }
      },
      deviceSizeSum: {
        type:'string',
        title:'门禁总容量',

        // minimum: 0,
        // maximum: 1024,
        ui:{
          grid: {span: 8},
        }
      },
    },
    "ui": {
      "spanLabelFixed": 150,
      "grid": {
        "span": 24
      }
    },
    required: []
  };
  schema2: SFSchema = {
    properties: {
      deviceOpenFace: {
        type: 'boolean',
        title: '人脸开门',
        ui: {
          checkedChildren: '开',
          unCheckedChildren: '关',
          grid: {span: 8}
        }
      },
      deviceBioAssay: {
        type: 'boolean',
        title: '活体检测',
        ui: {
          checkedChildren: '开',
          unCheckedChildren: '关',
          grid: {span: 8}
        }
      },
      deviceFaceSimilarity: {
        type:'number',
        title:'人脸比对相似阈值',
        minimum: 0,
        maximum: 100,
        ui:{
          grid: {span: 8}
        }
      },
      deviceBioAssaySimilarity: {
        type:'number',
        title:'活体检测阈值',
        minimum: 0,
        maximum: 100,
        ui:{
          grid: {span: 8}
        }
      },
      deviceFaceStorage: {
        type:'string',
        title:'人脸库存储上限',
        // minimum: 0,
        // maximum: 1024,
        readOnly:true,
        ui:{
          grid: {span: 8}
        }
      },
  
    },
    "ui": {
      "spanLabelFixed": 150,
      "grid": {
        "span": 24
      }
    },
    required: []
  };
  schema3: SFSchema = {
    properties: {
      deviceIntercom: {
        type: 'boolean',
        title: '对讲功能',
        ui: {
          checkedChildren: '开',
          unCheckedChildren: '关',
          hidden:false,
          grid: {span: 24}
        }
      },
      deviceVolumeCall: {
        type:'number',
        title:'门禁通话音量',
        minimum: 0,
        maximum: 100,
        ui: {
          widget:'slider',
          grid: {span: 12}
        } as SFSliderWidgetSchema
      },
      deviceVolumeAdvertising: {
        type:'number',
        title:'门禁广告音量',
        minimum: 0,
        maximum: 100,
        ui: {
          widget:'slider',
          grid: {span: 12}
        } as SFSliderWidgetSchema
      },
      deviceVolumeMic: {
        type:'number',
        title:'门禁mic增益',
        minimum: 0,
        maximum: 100,
        ui: {
          widget:'slider',
          grid: {span: 12}
        } as SFSliderWidgetSchema
      },
      deviceVolumeBell: {
        type:'number',
        title:'门禁铃声音量',
        minimum: 0,
        maximum: 100,
        ui: {
          widget:'slider',
          grid: {span: 12}
        } as SFSliderWidgetSchema
      },
      deviceVolumeHost: {
        type:'number',
        title:'门禁提示音量',
        minimum: 0,
        maximum: 100,
        ui: {
          widget:'slider',
          grid: {span: 12}
        } as SFSliderWidgetSchema
      },
    },
    "ui": {
      "spanLabelFixed": 150,
      "grid": {
        "span": 24
      }
    },
    required: []
  };
  schema4: SFSchema = {
    properties: {
      deviceId: {
        type: 'string',
        ui:{
          hidden:true
        }
      },
      deviceFacePat: {
        type: 'boolean',
        title: '人脸抓拍',
        ui: {
          checkedChildren: '开',
          unCheckedChildren: '关',
          grid: {span: 8}
        }
      },
      deviceFacePatVideoUpload: {
        type: 'boolean',
        title: '人脸抓拍视频上报',
        ui: {
          checkedChildren: '开',
          unCheckedChildren: '关',
          grid: {span :8}
        }
      },
      deviceShutScreen:{
        type:'boolean',
        title:'门禁息屏状态',
        ui: {
          checkedChildren: '开',
          unCheckedChildren: '关',
          grid:{span: 8}
        }
      },
      deviceAdvertising: {
        type: 'boolean',
        title: '门禁广告',
        ui: {
          checkedChildren: '开',
          unCheckedChildren: '关',
          grid: {span: 8}
        }
      },
      deviceAccessRecord: {
        type: 'boolean',
        title: '门禁出入记录上报',
        ui: {
          checkedChildren: '开',
          unCheckedChildren: '关',
          grid: {span :8}
        }
      },
      deviceAccessRecordPicture: {
        type: 'boolean',
        title: '门禁出入记录图片上报',
        ui: {
          checkedChildren: '开',
          unCheckedChildren: '关',
          grid: {span :8}
        }
      },
      deviceAccessRecordVideo: {
        type: 'boolean',
        title: '门禁出入记录视频上报',
        ui: {
          checkedChildren: '开',
          unCheckedChildren: '关',
          grid: {span :8}
        }
      },
      deviceLed: {
        type: 'boolean',
        title: '门禁LED灯状态',
        ui: {
          checkedChildren: '开',
          unCheckedChildren: '关',
          grid: {span :8}
        }
      },
      deviceAndroidPassword: {
        type:'string',
        title:'系统设置密码',
        ui: {
          type:'password',
          grid: {span: 8}
        }
      },
      deviceTamperAlarm: {
        type: 'boolean',
        title: '防拆报警',
        ui: {
          checkedChildren: '开',
          unCheckedChildren: '关',
          grid: {span :8}
        }
      },
      deviceDoorOpenAlarm: {
        type: 'boolean',
        title: '长开门报警',
        ui: {
          checkedChildren: '开',
          unCheckedChildren: '关',
          grid: {span :8}
        }
      },
      doorOpenTime: {
        type:'number',
        title:'开门时间',
        minimum: 5,
        maximum: 20,
        ui:{
          grid: {span: 8}
        }
      },
      deviceRemark: {
        type:'string',
        title:'备注'
      }
      // devicePasswordTemporary: {
      //   type: 'boolean',
      //   title: '临时密码',
      //   ui: {
      //     checkedChildren: '开',
      //     unCheckedChildren: '关',
      //     grid: {span: 8}
      //   }
      // },
      // devicePassword: {
      //   type:'string',
      //   title:'临时开门密码',
      //   ui: {
      //     type:'password',
      //     grid: {span: 8}
      //   }
      // },
      // devicePasswordTime: {
      //   type:'string',
      //   title:'临时密码有效期',
      //   format: 'date-time',
      //   ui: {
      //     grid: {span:8}
      //   }
      // },
      // deviceOpenQr: {
      //   type: 'boolean',
      //   title: '二维码开门',
      //   ui: {
      //     checkedChildren: '开',
      //     unCheckedChildren: '关',
      //     grid:{span : 8}
      //   }
      // },
      // deviceCamera: {
      //   type: 'boolean',
      //   title: '门禁摄像头',
      //   ui: {
      //     checkedChildren: '开',
      //     unCheckedChildren: '关',
      //     grid: {span :8}
      //   }
      // },

      // deviceVolumeHost: {
      //   type:'number',
      //   title:'门禁设备音量',
      //   minimum: 0,
      //   maximum: 100,
      //   ui: {
      //     widget:'slider',
      //     grid: {span: 12}
      //   } as SFSliderWidgetSchema
      // },
      // deviceVolumeAdvertising: {
      //   type:'number',
      //   title:'门禁广告音量',
      //   minimum: 0,
      //   maximum: 100,
      //   ui: {
      //     widget:'slider',
      //     grid: {span: 12}
      //   } as SFSliderWidgetSchema
      // },
   
    },
    "ui": {
      "spanLabelFixed": 150,
      "grid": {
        "span": 24
      }
    },
    required: ["deviceId"]
  }

  submitBase(data){
    this.submitData();
  }
  submitVersion(data){
    this.submitData();
  }
  formSubmit(data) {
    this.submitData();
  }

  submitData(){
    let baseData=this.formBase.value;
    let versionData=this.formVersion.value;
    let setData=this.formSet.value;
    console.log(baseData)
    baseData.deviceOpenFace = baseData.deviceOpenFace == true ? 1 : 0 ;
    baseData.deviceBioAssay = baseData.deviceBioAssay == true ? 1 : 0 ;
    versionData.deviceIntercom = versionData.deviceIntercom == true ? 1 : 0 ;
    setData.deviceFacePat = setData.deviceFacePat == true ? 1 : 0 ;
    setData.deviceFacePatVideoUpload = setData.deviceFacePatVideoUpload == true ? 1 : 0;
    setData.deviceShutScreen = setData.deviceShutScreen == true ? 1 : 0 ;
    setData.deviceAdvertising = setData.deviceAdvertising == true ? 1 : 0 ;
    setData.deviceAccessRecord = setData.deviceAccessRecord == true ? 1 : 0 ;
    setData.deviceAccessRecordPicture = setData.deviceAccessRecordPicture == true ? 1 : 0 ;
    setData.deviceAccessRecordVideo = setData.deviceAccessRecordVideo == true ? 1 : 0 ;
    setData.deviceLed = setData.deviceLed == true ? 1 : 0 ;
    setData.deviceTamperAlarm = setData.deviceTamperAlarm == true ? 1 : 0;
    setData.deviceDoorOpenAlarm = setData.deviceDoorOpenAlarm == true ? 1 : 0
    let body={...baseData,...versionData,...setData};
    body.deviceType = this.deviceType
    console.log(body);
    this.http.request<any>("post", "/core/host/rke/update",  { body}).subscribe(res => {
      if (res.status === '200') {
        this.msg.success('操作成功');
        //this.modalRef.destroy('ok');
      } else {
        this.msg.error(res.message)
      }
    })
  }

  getDeviceInfo(deviceId: string): Promise<any>{
    let body = {id:deviceId};
    return this.http.request<any>('POST', '/core/host/details',{body}).toPromise();
  }

  constructor(
    private api: ApiService,
    private http: HttpClient,
    private msg: NzMessageService,
    private util:UtilService,
    private modalRef: NzModalRef,
    private fb:FormBuilder
  ) { }

  async ngOnInit() {
    this.showForm = true;
    this.getHouses();
    if(this.deviceType == 8){
      this.schema3.properties["deviceIntercom"].ui["hidden"] = true
      this.formVersion.refreshSchema()
    }
    // this.validateForm = this.fb.group({
    //   btime:new Date(),
    //   etime:new Date(),
    //   cbtime:new Date(),
    //   cetime:new Date(),
    //   lbtime:new Date(),
    //   letime:new Date(),
    //   // rangePickerTime: [[new Date(this.param.cardUsingStartTime),new Date(this.param.cardUsingEndTime)]]
    // });
  }


  submitHouse(){
    let nodes=this.tree.getCheckedNodeList();
    if(nodes.length == 0){
      this.msg.error("请选择楼栋!");
      return;
    }
    const list = nodes.map(item=>{
      return {
       deviceId:this.param4.id,
       areaId: item.origin.id,
       areaParentAllName:item.origin.title,
       deviceDescribe:this.param4.deviceDescribe
      }
    })
    const url = '/core/host/hostBinding';
    const method = 'POST';
      this.http.request<any>(method, url, { body:list }).subscribe(res => {
        if (res.status === '200') {
          this.msg.success('操作成功');
          this.modalRef.triggerOk();
        } else {
          this.msg.error(res.message)
        }
      })
  }

    //获取楼栋列表
    getHouses(): void{
      this.http.post("/core/city/area/findDeviceBindingArea",{}).subscribe( (res:any) => {
        console.log(res);
        if (res.status === '200') {
          let list=[];
          for(let item of res.data){
            list.push({
              key:item.id,
              pId:item.areaId == undefined ? "" : item.areaId,
              title:item.areaParentAllName,
              id:item.id,
              value:item.id
            })
          }
          this.houseList=this.util.getTreeNodeOption(list)
          this.getlandlordManageUnitList()
        }
       
      })
    }
    resetForm(data){
      this.modalRef.destroy("ok");
     }

      //获取被绑定的楼栋
   getlandlordManageUnitList() : void{
    this.http.post("/core/area/host/queryList",{deviceId:this.param4.id}).subscribe((res:any) => {
      console.log(res)
      if (res.status === '200' && res.data && res.data.length > 0) {
        let list=[];
        for(let item of res.data){
          list.push(item.areaId)
        }
        this.defaultCheckedKeys=list;
      }
      this.isLoading=false;
    })
  }

}
